package com.kerry.netty;

import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.socket.DatagramPacket;
import io.netty.handler.timeout.ReadTimeoutException;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.kerry.dao.DataMessageDao;
import com.mysql.fabric.xmlrpc.base.Data;

@Component
public class ServerUDPHandler extends ChannelInboundHandlerAdapter {
	
	
	@Autowired
	private DataMessageDao msgDao;

	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ServerUDPHandler.class);
	
	
	public void test() {
		try {
			List<Map<String, String>> list = msgDao.findDataMessageList(new HashMap<String, Object>());
			System.out.println("list size:"+list.size());
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public ServerUDPHandler() {
	}

	@Override
	public void channelRead(ChannelHandlerContext ctx, Object msg)
			throws Exception {
		DatagramPacket dpaket = (DatagramPacket) msg;
		ByteBuf bbBuf = dpaket.content();
		byte[] byfs = new byte[bbBuf.readableBytes()];
		bbBuf.readBytes(byfs);
		logger.info("revice data from address :"+dpaket.sender().getHostName()+
				"port :"+dpaket.sender().getPort()+"---->"+
				new String(byfs, Charset.forName("UTF-8")));
		
		
		
		//return msg to client..
		DatagramPacket dp = new DatagramPacket(Unpooled.copiedBuffer("消息".getBytes()), dpaket.sender());  
        ctx.channel().writeAndFlush(dp);  
		//other business ,example database query..
//		test();
	}

	@Override
	public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause)
			throws Exception {
		if (cause instanceof ReadTimeoutException) {

			// eventChatLauncher.sendTimeout(); //全局超时

		} else {
			ctx.channel().close();
			// super.exceptionCaught(ctx, cause);

		}
	}

}
